import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  FaSpider, 
  FaTasks, 
  FaCogs, 
  FaDatabase, 
  FaChartBar,
  FaPlay,
  FaStop,
  FaSync,
  FaExclamationTriangle,
  FaPlus,
  FaInfoCircle,
  FaProjectDiagram
} from 'react-icons/fa';
import { motion } from 'framer-motion';
import { crawlerApi } from '../../services/crawlerApi';
import { useAuthStore } from '../../stores/authStore';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import CustomButton from '../../components/custom/CustomButton';
import CustomCard from '../../components/custom/CustomCard';
import CustomLineChart from '../../components/charts/CustomLineChart';
import CustomProgressBar from '../../components/custom/CustomProgressBar';
import './CrawlerPage.css';

const CrawlerPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [scrapydStatus, setScrapydStatus] = useState<any>(null);
  const [projects, setProjects] = useState<string[]>([]);
  const [showHelp, setShowHelp] = useState(false);
  const [chartData, setChartData] = useState<{x: string; y: number}[]>([]);
  const [taskProgress, setTaskProgress] = useState(0);

  // 检查认证状态
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [navigate]); // 移除isAuthenticated依赖以避免无限循环

  // 获取Scrapyd状态和项目列表
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 获取Scrapyd状态
        const status = await crawlerApi.getScrapydStatus();
        setScrapydStatus(status);
        
        // 获取项目列表
        const projectsData = await crawlerApi.getScrapydProjects();
        // 添加安全检查，确保projectsData存在且包含projects属性
        if (projectsData && Array.isArray(projectsData.projects)) {
          setProjects(projectsData.projects);
        } else {
          setProjects([]);
        }
        
        // 生成示例图表数据
        const data = [];
        for (let i = 6; i >= 0; i--) {
          const date = new Date();
          date.setDate(date.getDate() - i);
          data.push({
            x: `${date.getMonth() + 1}/${date.getDate()}`,
            y: Math.floor(Math.random() * 100) + 50
          });
        }
        setChartData(data);
        
        // 模拟任务进度
        setTaskProgress(Math.floor(Math.random() * 100));
      } catch (err) {
        console.error('获取爬虫数据失败:', err);
        setError('获取爬虫数据失败: ' + (err instanceof Error ? err.message : '未知错误'));
        // 发生错误时设置空的项目列表
        setProjects([]);
      } finally {
        setLoading(false);
      }
    };

    if (isAuthenticated) {
      fetchData();
    }
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  if (!isAuthenticated) {
    return null;
  }

  if (loading) {
    return (
      <div className="crawler-page-container" style={{ color: theme.textPrimary }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '100%', 
          color: theme.textPrimary 
        }}>
          <div className="flex items-center">
            <motion.div
              animate={{ rotate: 360 }}
              transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
            >
              <FaSpider style={{ color: theme.glowColor, fontSize: '24px', marginRight: '12px' }} />
            </motion.div>
            <span style={{ fontSize: '18px', fontWeight: '500' }}>加载中...</span>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="crawler-page-container">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <div style={{ 
            padding: '16px',
            borderRadius: '8px',
            backgroundColor: mode === 'dark' ? 'rgba(255, 77, 79, 0.1)' : 'rgba(255, 77, 79, 0.05)',
            border: `1px solid ${mode === 'dark' ? 'rgba(255, 77, 79, 0.3)' : 'rgba(255, 77, 79, 0.2)'}`,
            color: theme.textPrimary
          }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
              <FaExclamationTriangle style={{ color: '#ff4d4f', marginRight: '8px' }} />
              <strong>错误</strong>
            </div>
            <div>{error}</div>
          </div>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="crawler-page-container">
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div style={{ marginBottom: '24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <motion.h1 
              className="crawler-page-title"
              whileHover={{ scale: 1.02 }}
            >
              <motion.div
                animate={{ rotate: 360 }}
                transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
                whileHover={{ scale: 1.2 }}
              >
                <FaSpider style={{ marginRight: '12px' }} />
              </motion.div>
              智能爬虫系统
            </motion.h1>
            <motion.p 
              className="crawler-page-subtitle"
              initial={{ opacity: 0 }}
              animate={{ opacity: 0.8 }}
              transition={{ delay: 0.3, duration: 0.5 }}
            >
              支持静态/动态网页爬取，分布式任务调度
            </motion.p>
          </div>
          <div style={{ display: 'flex', gap: '12px' }}>
            <CustomButton 
              type="primary" 
              icon={<FaPlus />}
              onClick={() => navigate('/crawler/tasks/new')}
            >
              新建任务
            </CustomButton>
            <CustomButton 
              icon={<FaInfoCircle />}
              onClick={() => setShowHelp(!showHelp)}
            >
              帮助
            </CustomButton>
          </div>
        </div>

        {/* 帮助信息 */}
        {showHelp && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.3 }}
            style={{ marginBottom: '24px' }}
          >
            <CustomCard>
              <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                <FaInfoCircle style={{ color: theme.glowColor, fontSize: '20px', marginRight: '12px', marginTop: '2px' }} />
                <div>
                  <h3 style={{ color: theme.textPrimary, marginBottom: '8px' }}>使用指南</h3>
                  <ul style={{ paddingLeft: '20px', color: theme.textSecondary }}>
                    <li>在"爬虫任务"中创建和管理您的爬虫任务</li>
                    <li>使用"定时任务"配置定期执行的爬虫任务</li>
                    <li>在"数据管理"中查看和导出爬取的数据</li>
                    <li>通过"监控面板"实时查看爬虫运行状态</li>
                  </ul>
                </div>
              </div>
            </CustomCard>
          </motion.div>
        )}

        {/* 状态卡片 */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
          <motion.div
            whileHover={{ y: -5 }}
            whileTap={{ scale: 0.98 }}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1, duration: 0.3 }}
          >
            <CustomCard className="crawler-status-card theme-transition">
              <div style={{ padding: '20px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <motion.div 
                    className="crawler-status-card-icon-container"
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaPlay className="crawler-status-card-icon" />
                  </motion.div>
                  <div>
                    <div className="crawler-status-card-title">
                      Scrapyd状态
                    </div>
                    <motion.div 
                      className="crawler-status-card-value"
                      whileHover={{ scale: 1.05 }}
                    >
                      {scrapydStatus?.status === 'ok' ? '运行中' : '未知'}
                    </motion.div>
                  </div>
                </div>
              </div>
              <div 
                style={{ 
                  position: 'absolute', 
                  top: 0, 
                  left: 0, 
                  right: 0, 
                  height: '3px',
                  background: `linear-gradient(90deg, transparent, ${theme.glowColor}, transparent)`,
                  opacity: 0.7,
                  animation: 'shimmer 2s infinite'
                }} 
              />
            </CustomCard>
          </motion.div>

          <motion.div
            whileHover={{ y: -5 }}
            whileTap={{ scale: 0.98 }}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2, duration: 0.3 }}
          >
            <CustomCard className="crawler-status-card theme-transition">
              <div style={{ padding: '20px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <motion.div 
                    className="crawler-status-card-icon-container"
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaDatabase className="crawler-status-card-icon" />
                  </motion.div>
                  <div>
                    <div className="crawler-status-card-title">
                      项目数量
                    </div>
                    <motion.div 
                      className="crawler-status-card-value"
                      whileHover={{ scale: 1.05 }}
                    >
                      {projects ? projects.length : 0}
                    </motion.div>
                  </div>
                </div>
              </div>
              <div 
                style={{ 
                  position: 'absolute', 
                  top: 0, 
                  left: 0, 
                  right: 0, 
                  height: '3px',
                  background: `linear-gradient(90deg, transparent, ${theme.glowColor}, transparent)`,
                  opacity: 0.7,
                  animation: 'shimmer 2s infinite'
                }} 
              />
            </CustomCard>
          </motion.div>

          <motion.div
            whileHover={{ y: -5 }}
            whileTap={{ scale: 0.98 }}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3, duration: 0.3 }}
          >
            <CustomCard className="crawler-status-card theme-transition">
              <div style={{ padding: '20px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <motion.div 
                    className="crawler-status-card-icon-container"
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaTasks className="crawler-status-card-icon" />
                  </motion.div>
                  <div>
                    <div className="crawler-status-card-title">
                      任务队列
                    </div>
                    <motion.div 
                      className="crawler-status-card-value"
                      whileHover={{ scale: 1.05 }}
                    >
                      0
                    </motion.div>
                  </div>
                </div>
              </div>
              <div 
                style={{ 
                  position: 'absolute', 
                  top: 0, 
                  left: 0, 
                  right: 0, 
                  height: '3px',
                  background: `linear-gradient(90deg, transparent, ${theme.glowColor}, transparent)`,
                  opacity: 0.7,
                  animation: 'shimmer 2s infinite'
                }} 
              />
            </CustomCard>
          </motion.div>

          <motion.div
            whileHover={{ y: -5 }}
            whileTap={{ scale: 0.98 }}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4, duration: 0.3 }}
          >
            <CustomCard className="crawler-status-card theme-transition">
              <div style={{ padding: '20px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <motion.div 
                    className="crawler-status-card-icon-container"
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaChartBar className="crawler-status-card-icon" />
                  </motion.div>
                  <div>
                    <div className="crawler-status-card-title">
                      今日爬取
                    </div>
                    <motion.div 
                      className="crawler-status-card-value"
                      whileHover={{ scale: 1.05 }}
                    >
                      0
                    </motion.div>
                  </div>
                </div>
              </div>
              <div 
                style={{ 
                  position: 'absolute', 
                  top: 0, 
                  left: 0, 
                  right: 0, 
                  height: '3px',
                  background: `linear-gradient(90deg, transparent, ${theme.glowColor}, transparent)`,
                  opacity: 0.7,
                  animation: 'shimmer 2s infinite'
                }} 
              />
            </CustomCard>
          </motion.div>
        </div>

        {/* 数据可视化图表 */}
        <div className="mb-6">
          <motion.h2 
            className="crawler-module-title"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.5, duration: 0.3 }}
          >
            爬取数据趋势
          </motion.h2>
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.6, duration: 0.3 }}
          >
            <CustomCard>
              <CustomLineChart 
                data={chartData} 
                title="近7天数据爬取量" 
                height={300}
                color={mode === 'dark' ? '#61dca3' : '#1890ff'}
              />
            </CustomCard>
          </motion.div>
        </div>

        {/* 任务进度 */}
        <div className="mb-6">
          <motion.h2 
            className="crawler-module-title"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.7, duration: 0.3 }}
          >
            当前任务进度
          </motion.h2>
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.8, duration: 0.3 }}
          >
            <CustomCard>
              <div style={{ padding: '20px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
                  <span style={{ color: theme.textPrimary, fontWeight: '500' }}>数据爬取任务</span>
                  <span style={{ color: theme.textSecondary }}>{taskProgress}%</span>
                </div>
                <CustomProgressBar percent={taskProgress} showInfo={false} />
                <div style={{ 
                  display: 'flex', 
                  justifyContent: 'space-between', 
                  marginTop: '12px',
                  color: theme.textSecondary,
                  fontSize: '14px'
                }}>
                  <span>预计剩余时间: 5分钟</span>
                  <span>已爬取: 1,245 条数据</span>
                </div>
              </div>
            </CustomCard>
          </motion.div>
        </div>

        {/* 功能模块 */}
        <div className="crawler-module-section">
          <motion.h2 
            className="crawler-module-title"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.9, duration: 0.3 }}
          >
            功能模块
          </motion.h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <motion.div
              whileHover={{ y: -8, scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.0, duration: 0.3 }}
            >
              <div 
                className="crawler-module-card theme-transition"
                onClick={() => navigate('/crawler/tasks')}
              >
                <div style={{ padding: '24px', textAlign: 'center' }}>
                  <motion.div 
                    className="crawler-module-icon-container"
                    whileHover={{ scale: 1.1, rotate: 10 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaTasks className="crawler-module-icon" />
                  </motion.div>
                  <motion.h3 
                    className="crawler-module-card-title"
                    whileHover={{ scale: 1.05 }}
                  >
                    爬虫任务
                  </motion.h3>
                  <p className="crawler-module-card-description">
                    创建和管理爬虫任务
                  </p>
                </div>
              </div>
            </motion.div>

            <motion.div
              whileHover={{ y: -8, scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.1, duration: 0.3 }}
            >
              <div 
                className="crawler-module-card theme-transition"
                onClick={() => navigate('/crawler/scheduler')}
              >
                <div style={{ padding: '24px', textAlign: 'center' }}>
                  <motion.div 
                    className="crawler-module-icon-container"
                    whileHover={{ scale: 1.1, rotate: 10 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaCogs className="crawler-module-icon" />
                  </motion.div>
                  <motion.h3 
                    className="crawler-module-card-title"
                    whileHover={{ scale: 1.05 }}
                  >
                    定时任务
                  </motion.h3>
                  <p className="crawler-module-card-description">
                    配置定时爬虫任务
                  </p>
                </div>
              </div>
            </motion.div>

            <motion.div
              whileHover={{ y: -8, scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.2, duration: 0.3 }}
            >
              <div 
                className="crawler-module-card theme-transition"
                onClick={() => navigate('/crawler/data')}
              >
                <div style={{ padding: '24px', textAlign: 'center' }}>
                  <motion.div 
                    className="crawler-module-icon-container"
                    whileHover={{ scale: 1.1, rotate: 10 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaDatabase className="crawler-module-icon" />
                  </motion.div>
                  <motion.h3 
                    className="crawler-module-card-title"
                    whileHover={{ scale: 1.05 }}
                  >
                    数据管理
                  </motion.h3>
                  <p className="crawler-module-card-description">
                    查看和导出爬取数据
                  </p>
                </div>
              </div>
            </motion.div>

            <motion.div
              whileHover={{ y: -8, scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.3, duration: 0.3 }}
            >
              <div 
                className="crawler-module-card theme-transition"
                onClick={() => navigate('/crawler/config')}
              >
                <div style={{ padding: '24px', textAlign: 'center' }}>
                  <motion.div 
                    className="crawler-module-icon-container"
                    whileHover={{ scale: 1.1, rotate: 10 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaCogs className="crawler-module-icon" />
                  </motion.div>
                  <motion.h3 
                    className="crawler-module-card-title"
                    whileHover={{ scale: 1.05 }}
                  >
                    配置管理
                  </motion.h3>
                  <p className="crawler-module-card-description">
                    管理爬虫配置和规则
                  </p>
                </div>
              </div>
            </motion.div>

            <motion.div
              whileHover={{ y: -8, scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.4, duration: 0.3 }}
            >
              <div 
                className="crawler-module-card theme-transition"
                onClick={() => navigate('/crawler/monitor')}
              >
                <div style={{ padding: '24px', textAlign: 'center' }}>
                  <motion.div 
                    className="crawler-module-icon-container"
                    whileHover={{ scale: 1.1, rotate: 10 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaChartBar className="crawler-module-icon" />
                  </motion.div>
                  <motion.h3 
                    className="crawler-module-card-title"
                    whileHover={{ scale: 1.05 }}
                  >
                    监控面板
                  </motion.h3>
                  <p className="crawler-module-card-description">
                    实时监控爬虫状态
                  </p>
                </div>
              </div>
            </motion.div>

            <motion.div
              whileHover={{ y: -8, scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.5, duration: 0.3 }}
            >
              <div 
                className="crawler-module-card theme-transition"
                onClick={() => navigate('/crawler/logs')}
              >
                <div style={{ padding: '24px', textAlign: 'center' }}>
                  <motion.div 
                    className="crawler-module-icon-container"
                    whileHover={{ scale: 1.1, rotate: 10 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <FaSync className="crawler-module-icon" />
                  </motion.div>
                  <motion.h3 
                    className="crawler-module-card-title"
                    whileHover={{ scale: 1.05 }}
                  >
                    日志查看
                  </motion.h3>
                  <p className="crawler-module-card-description">
                    查看爬虫执行日志
                  </p>
                </div>
              </div>
            </motion.div>
          </div>
        </div>

        {/* 项目列表 */}
        <div className="crawler-project-section">
          <motion.h2 
            className="crawler-project-title"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 1.6, duration: 0.3 }}
          >
            <FaProjectDiagram style={{ marginRight: '8px' }} />
            已部署项目
          </motion.h2>
          
          {(projects && projects.length > 0) ? (
            <motion.div
              className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 1.7, duration: 0.5 }}
            >
              {projects.map((project, index) => (
                <motion.div
                  key={index}
                  whileHover={{ y: -5 }}
                  whileTap={{ scale: 0.98 }}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 1.8 + index * 0.1, duration: 0.3 }}
                >
                  <div 
                    className="crawler-project-card theme-transition"
                    onClick={() => navigate(`/crawler/projects/${project}`)}
                  >
                    <div style={{ padding: '20px' }}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <motion.div 
                          className="crawler-project-icon-container"
                          whileHover={{ scale: 1.1 }}
                          whileTap={{ scale: 0.9 }}
                        >
                          <FaSpider className="crawler-project-icon" />
                        </motion.div>
                        <div>
                          <motion.div 
                            className="crawler-project-name"
                            whileHover={{ scale: 1.05 }}
                          >
                            {project}
                          </motion.div>
                          <div className="crawler-project-description">
                            点击查看详情
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </motion.div>
              ))}
            </motion.div>
          ) : (
            <motion.div
              whileHover={{ y: -5 }}
              whileTap={{ scale: 0.98 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.8, duration: 0.3 }}
            >
              <div className="crawler-project-card theme-transition">
                <div className="crawler-empty-state">
                  <motion.div
                    animate={{ 
                      scale: [1, 1.1, 1],
                      rotate: [0, 5, -5, 0]
                    }}
                    transition={{ 
                      duration: 2,
                      repeat: Infinity,
                      repeatType: "reverse"
                    }}
                  >
                    <FaSpider className="crawler-empty-state-icon" />
                  </motion.div>
                  <p className="crawler-empty-state-title">
                    暂无已部署的爬虫项目
                  </p>
                  <p className="crawler-empty-state-description">
                    请先部署Scrapy项目到Scrapyd服务器
                  </p>
                </div>
              </div>
            </motion.div>
          )}
        </div>
      </motion.div>
      
      {/* 添加动画样式 */}
      <style>{`
        @keyframes shimmer {
          0% {
            transform: translateX(-100%);
          }
          100% {
            transform: translateX(100%);
          }
        }
      `}</style>
    </div>
  );
};

export default CrawlerPage;